<template>
  <div class="pagination-container">
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPageProxy"
        v-model:page-size="pageSizeProxy"
        :page-sizes="pageSizes"
        :total="total"
        layout="sizes, prev, pager, next"
        :pager-count="5"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <!-- 自定义跳转输入框 -->
      <div class="custom-jumper">
        前往第
        <el-input
          v-model="jumpPage"
          class="jump-input"
          type="number"
          :min="1"
          :max="maxPage"
          @keyup.enter="handleJumpChange"
        />
        页
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, watch } from 'vue'

const props = defineProps({
  currentPage: {
    type: Number,
    required: true
  },
  pageSize: {
    type: Number,
    required: true
  },
  total: {
    type: Number,
    required: true
  },
  pageSizes: {
    type: Array,
    // default: () => [10, 20, 30, 50] 
    required: true
  }
})

const emit = defineEmits(['update:currentPage', 'update:pageSize', 'pagination-change'])

// 计算最大页数
const maxPage = computed(() => Math.ceil(props.total / props.pageSize))

// 跳转页码
const jumpPage = ref(props.currentPage)

// 监听当前页变化，同步跳转输入框
watch(() => props.currentPage, (newVal) => {
  jumpPage.value = newVal
})

const currentPageProxy = computed({
  get: () => props.currentPage,
  set: (val) => emit('update:currentPage', val)
})

const pageSizeProxy = computed({
  get: () => props.pageSize,
  set: (val) => emit('update:pageSize', val)
})

const handleSizeChange = (val) => {
  emit('pagination-change', {
    type: 'size',
    value: val
  })
}

const handleCurrentChange = (val) => {
  emit('pagination-change', {
    type: 'page',
    value: val
  })
}

// 修改跳转页码处理函数
const handleJumpChange = () => {
  const pageNum = parseInt(jumpPage.value)
  if (pageNum && pageNum >= 1 && pageNum <= maxPage.value) {
    currentPageProxy.value = pageNum
    emit('pagination-change', {
      type: 'page',
      value: pageNum
    })
  } else {
    jumpPage.value = props.currentPage
  }
}
</script>

<style scoped>
.pagination-container {
  width: 100%;
  margin-top: 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 0 20px;
  gap: 16px;
}

.custom-jumper {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

.jump-input {
  width: 50px;
  margin: 0 8px;
}

/* 处理跳转输入框的样式 */
:deep(.jump-input .el-input__inner) {
  text-align: center;
  padding: 0 4px;
  height: 28px;
  appearance: textfield;
  -moz-appearance: textfield;
}

:deep(.jump-input .el-input__inner::-webkit-outer-spin-button),
:deep(.jump-input .el-input__inner::-webkit-inner-spin-button) {
  -webkit-appearance: none;
  margin: 0;
}

:deep(.el-pagination) {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
</style> 